import pandas as pd
import numpy as np
df = pd.DataFrame()
# 时间转换， 日期转字符串
df["min"] = df.day.apply(lambda x: x.strftime("%H:%M"))
# 字符串转日期
df["day"] = pd.to_datetime(df.day_str, format="%Y-%m-%d %H:%M:%S")

### 字符串截取
df["min"] = df["day"].apply(lambda x: x[-8:])

# 最后统一保留3位小数
df.round(3)
# 针对不同列保留小鼠
df.round({'dogs': 2, 'cats': 1})
# 删除列
del df['A'] # 删除A列，会就地修改
df= df.drop(['B','C'], axis=1)              # drop不会就地修改，创建副本返回
df.drop(['B','C'], axis=1, inplace=True)     # inplace=True会就地修改
# 删除行
df = df.drop(df[df.score < 50].index)
df.dropna(axis=0, how='any') # any 表示任何一个字段为None 就删除该行，all 表示全为NAN 才删除
df = df.drop(df[df.score < 50].index) # 按照条件删除行
df.drop(df[df.return5.isna()].index)

# 获取
data = get_price(['000001.SZ', '600519.SH'], '20190301', '20190311', '1d', ['close', 'turnover'], True, None, 0, is_panel=1)
df = data.to_frame().reset_index()

"""
df 
	major	minor	close	turnover
0	2019-03-01	000001.SZ	12.76	2.137670e+09
1	2019-03-01	600519.SH	789.30	4.952509e+09
"""

# 重命名数据列名

df.columns = ['date', 'symbol', 'close', 'turnover']
# 排序 重置index
df = df.sort_values(['symbol', 'date'])
df = df.reset_index(drop=True)
# 获取股票名
info = get_all_securities('stock', '20190301').reset_index()
info = info[['symbol', 'display_name']]
# 将股票名称拼接到行情数据上
df = pd.merge(df, info, how='left', on=['symbol'])
# 改变列顺序
df = df[['date', 'symbol', 'display_name', 'close', 'turnover']]

# 筛选
df_sub_1 = df[df['symbol'] == '000001.SZ']

# 收盘价比例， 结果中为NaN的地方表示空值
df['return'] = df['close'] / df.groupby(['symbol'])['close'].shift(1) - 1.0
"""
	date	symbol	display_name	close	turnover	return
0	2019-03-01	000001.SZ	平安银行	12.76	2.137670e+09	NaN
1	2019-03-04	000001.SZ	平安银行	12.99	3.195012e+09	0.018025
2	2019-03-05	000001.SZ	平安银行	13.06	1.838252e+09	0.005389
3	2019-03-06	000001.SZ	平安银行	13.08	1.614671e+09	0.001531
4	2019-03-07	000001.SZ	平安银行	12.74	2.274151e+09	-0.025994
5	2019-03-08	000001.SZ	平安银行	12.30	2.214572e+09	-0.034537
6	2019-03-11	000001.SZ	平安银行	12.32	1.416000e+09	0.001626
7	2019-03-01	600519.SH	贵州茅台	789.30	4.952509e+09	NaN
8	2019-03-04	600519.SH	贵州茅台	781.86	6.661387e+09	-0.009426
"""
# 移动均线 5
df['close_ma5'] = df.groupby(['symbol'])['close'].rolling(5).mean().reset_index(drop=True, level=0)

# 导出

df.to_csv(r'./新手教程数据导出.csv', index=False)

### 选取10日涨幅小于7% 60日涨幅大于40%的股票
data['ret_10'] = data['close'] / data.groupby(['symbol'])['close'].shift(10) - 1.0
data['ret_60'] = data['close'] / data.groupby(['symbol'])['close'].shift(60) - 1.0
data_req = data[data['date'] == date_str]
result = data_req[(data_req['ret_10'] < 0.07) & (data_req['ret_60'] > 0.40)]
print(result['symbol'].values.tolist())

# DataFrame.resample()
#按1小时聚合,取平均值
df.resample(rule='1H').mean()
#按1分钟聚合，取最大值
df.resample(rule='1T').max()
